!(function () {
    "use strict";

    const canvas = document.querySelector('canvas').getContext('2d');

    const { PI } = Math;

    /* 创建两个矩形 */
    const r1 = new Rectangle(50, 150, 150, 100);
    const r2 = new Rectangle(170, 230, 200, 70);

    /* 创建矩形的绘制参数 */
    const r1RenderOption = {
        rect: r1,
        background: 'rgba(0,0,0,0.3)'
    };

    const r2RenderOption = {
        rect: r2,
        background: 'rgba(0,255,0,0.3)'
    };

    bindUIEvent();

    render();

    /*         函数声明部分         */

    /** Canvas 绘制主函数 */
    function render() {
        canvas.clearRect(0, 0, 500, 500);

        //如果矩形产生重叠，修改其中一个矩形的背景色
        r2RenderOption.background = isOverlap(r1, r2) ? 'rgba(255,0,0,0.7)' : 'rgba(0,255,0,0.3)';

        drawRectangle(r1RenderOption);
        drawRectangle(r2RenderOption);
    }

    /** 绘制矩形 */
    function drawRectangle({ rect, background }) {

        canvas.save();
        canvas.fillStyle = background;

        if (!rect.rotate) {
            //如果矩形没有旋转，则直接绘制
            canvas.fillRect(rect.x, rect.y, rect.width, rect.height);
        } else {
            //如果矩形有旋转，则使用路径填充
            canvas.beginPath();
            rect.getRealVertex().map(function ({ x, y }, index) {
                if (index === 0) {
                    canvas.moveTo(x, y);
                } else {
                    canvas.lineTo(x, y);
                }
            });
            canvas.fill();
        }

        canvas.restore();
    }

    /** 绑定页面输入事件 */
    function bindUIEvent() {
        const rotateLabel1 = document.querySelector('#spanRotate1');
        document.querySelector('#inputRotate1').addEventListener('input', function (e) {
            rotateLabel1.textContent = `${this.value}度`;
            r1.rotate = common.toRad(this.value);
            render();
        });

        const rotateLabel2 = document.querySelector('#spanRotate2');
        document.querySelector('#inputRotate2').addEventListener('input', function (e) {
            rotateLabel2.textContent = `${this.value}度`;
            r2.rotate = common.toRad(this.value);
            render();
        });
    }
})();